/*
Copyright (C) 1996-1997 Id Software, Inc.

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 3
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

*/

#include "fxVSIncludes.fx"

struct VS_SKY
{
	float4 Position : POSITION;
};

struct PS_SKY
{
	float4 Position : SV_POSITION;
	float3 TexCoord : TEXCOORD;
};


#ifdef VERTEXSHADER
PS_SKY SkyWarpVS (VS_SKY vs_in)
{
	PS_SKY vs_out;

	// flatten the sphere
	float4x4 SkyMatrix = float4x4 (
		float4 (1, 0, 0, -EyePositionWorld.x),
		float4 (0, 1, 0, -EyePositionWorld.y),
		float4 (0, 0, 1, -EyePositionWorld.z) * 3.0f,
		float4 (0, 0, 0, 1)
	);

	vs_out.Position = mul (EntityMatrix, mul (LocalMatrix, vs_in.Position));
	vs_out.TexCoord = mul (SkyMatrix, mul (LocalMatrix, vs_in.Position)).xyz;

	return vs_out;
}

PS_SKY SkyCubeVS (VS_SKY vs_in)
{
	PS_SKY vs_out;

	// this is z-going-up with rotate and flip to orient the sky correctly
	float4x4 SkyMatrix = float4x4 (
		float4 (0, 1, 0, -EyePositionWorld.y) * -1.0f,
		float4 (0, 0, 1, -EyePositionWorld.z),
		float4 (1, 0, 0, -EyePositionWorld.x),
		float4 (0, 0, 0, 1)
	);

	vs_out.Position = mul (EntityMatrix, mul (LocalMatrix, vs_in.Position));
	vs_out.TexCoord = mul (SkyMatrix, mul (LocalMatrix, vs_in.Position)).xyz;

	return vs_out;
}
#endif


#ifdef PIXELSHADER
// set once only so they can be held and never need checking
Texture2D solidTexture : register(TEXTURE_SLOT_SOLIDSKY);
Texture2D alphaTexture : register(TEXTURE_SLOT_ALPHASKY);
TextureCube SkyCubeMap : register(TEXTURE_SLOT_CUBESKY);

float4 SkyWarpPS (PS_SKY ps_in) : SV_TARGET0
{
	float3 skycoord = normalize (ps_in.TexCoord) * 2.953125f;

	float4 solidColor = solidTexture.Sample (surfSampler, skycoord.xy + SkySpeedScale.x);
	float4 alphaColor = alphaTexture.Sample (surfSampler, skycoord.xy + SkySpeedScale.y);

	return lerp (solidColor, alphaColor, alphaColor.a);
}

float4 SkyCubePS (PS_SKY ps_in) : SV_TARGET0
{
	// cubemaps rock
	return SkyCubeMap.Sample (surfSampler, ps_in.TexCoord);
}
#endif

